package com.jcl.cloud.services.crawler.brain.service;

import com.jcl.cloud.services.crawler.brain.task.WorkerService;
import com.jcl.cloud.services.unicrawler.client.CrawlerManagerClient;
import com.jcl.cloud.services.unicrawler.common.dto.GrabRequest;
import com.jcl.cloud.services.unicrawler.common.dto.GrabResult;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



@Service
public class GrabCrawlerWorkerService implements WorkerService {
    private static final Logger logger = LoggerFactory.getLogger(GrabCrawlerWorkerService.class);


    @Autowired
    private CrawlerManagerClient crawlerManagerClient;

    @Override
    public Object doWorker(String traceId) {

        GrabRequest grabRequest = this.createGrabRequestObj(traceId);
        logger.debug("grabTask request: {}", grabRequest);
        GrabResult grabResult = this.crawlerManagerClient.grabTask(grabRequest);
        if (StringUtils.isBlank(grabResult.getCrawlerId())) {
            logger.debug("grab task fail,resp:{}.", grabResult);
            return null;
        } else {
            logger.info("grab task success , resp: {}",grabResult);

            return grabResult;
        }
    }



    private GrabRequest createGrabRequestObj(String traceId) {
        GrabRequest grabRequest = new GrabRequest();
        grabRequest.setTraceId(traceId);
        grabRequest.setWorkerName("crawler-brain");
        return grabRequest;
    }

}
